#include "mainwindow.h"

#include <QApplication>

#include "user_login_widget.h"
#include "global_config.h"
#include "game_widget.h"
#include "mainwidget.h"

#include <QDebug>
#include <thread>

int handleUserLogin(QWidget *parent, std::shared_ptr<tcp_client> client)
{
    auto *userLoginWgt = new UserLoginWidget(nullptr, client);

    // auto userLoginWgtPtr = std::make_shared<UserLoginWidget>();

    userLoginWgt->show();

    return 0;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    std::shared_ptr<tcp_client> client_ptr = nullptr;

    net::io_context ioc;

    client_ptr = std::make_shared<tcp_client>(ioc);
    net::ip::address addr = net::ip::make_address("172.20.107.104");
    tcp::endpoint endpoint(net::ip::address(addr), 12345);
    client_ptr->start(endpoint);

    std::thread t([&ioc]() {
        ioc.run();
    });

    auto userLoginWgt = std::make_shared<UserLoginWidget>(nullptr, client_ptr);

    network_message_handler &msg_handler = network_message_handler::get_instance();
    msg_handler.setUserLoginWidget(userLoginWgt);
    userLoginWgt->exec();

    if (!userLoginWgt->isLoginSuccess()) {
        a.closeAllWindows();
        return 0;
    }

    auto mainWgt =  std::make_shared<MainWidget>(nullptr, client_ptr);
    mainWgt->show();
    msg_handler.setMainWidget(mainWgt);

    auto gameWgt = std::make_shared<GameWidget>(nullptr, client_ptr);
    msg_handler.setGameWidget(gameWgt);

    // MainWindow mainWindow(nullptr, client_ptr);
    // msg_handler.setMainWindow(&mainWindow);

    auto mineSweeperWgt = gameWgt->mineSweeperWidget();
    mineSweeperWgt->setGameWidget(gameWgt);
    msg_handler.setMineSweeprWidget(mineSweeperWgt);


    // mainWindow.show();

    // gameWgt->show();
    gameWgt->setWindowTitle("扫雷游戏");

    t.detach();
    return a.exec();
}
